<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form  :model="formData" ref="formData" label-width="100px" slot="form" :rules="rules">
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称">
                            <school v-model.trim="formData.schoolName" :provinceId="formData.fProvinceId" :cityId="formData.fCityId" :areaId="formData.fAreaId" style="width:100%" @change='schoolChange'></school>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="充值手机号" >
                            <el-input  placeholder="请输入手机号" v-model.trim="formData.phone" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="8">
                        <el-form-item label="姓名">
                            <el-input  placeholder="请输入姓名" v-model.trim="formData.name"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="e学云ID号" prop="exueID">
                            <el-input  placeholder="请输入e学云ID号" v-model.trim="formData.exueID" :maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态">
                            <el-select v-model="formData.state" placeholder="请选择" style="width:100%">
                                <el-option 
                                v-for="item in formData.options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="领取日期" >
                            <el-date-picker style="width:100%"
                            type="daterange"
                            :editable="false"
                            placeholder="开始日期~结束日期" v-model="formData.daterange">
                            </el-date-picker>
                        </el-form-item>
                    </el-col> 
                </el-row>
                <div class="top-line">
                    <el-button type="primary" @click="onSubmit()">查询</el-button>
                </div>
            </el-form>

            <div class="table-title" slot="table-title"></div>
            <el-button :plain="true"  class="addButton" @click="recharge">确认充值</el-button>
            <!--<el-button :plain="true"  class="addButton" @click="delDetail">删除</el-button>!-->
            <el-button :plain="true"  class="addButton" @click="toExcel">导出</el-button>

            <el-table ref="multipleTable" :data="detailList" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :selectable="fn"></el-table-column>
                <el-table-column label="学校" align="center" prop="schoolName"> </el-table-column>
                <el-table-column label="充值手机号" align="center" prop="rechargePhone"> </el-table-column>
                <el-table-column label="注册手机号" align="center" prop="regPhone"> </el-table-column>
                <el-table-column label="姓名" align="center" prop="teacherName"> </el-table-column>
                <el-table-column label="e学云ID号" align="center" prop="exueCode"> </el-table-column>
                <el-table-column label="状态" align="center"> 
                    <template scope="scope">
                        <span v-if='scope.row.status === "1"'>待充值</span>
                        <span v-if='scope.row.status === "0"'>已充值</span>
                    </template>
                </el-table-column>
                <el-table-column label="领取时间" align="center" prop="date"> 
                    <template scope="scope">
                        <span>{{scope.row.receiveTime || '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="充值时间" align="center" prop="date"> 
                    <template scope="scope">
                        <span>{{scope.row.rechargeTime || '--' }}</span>
                    </template>
                </el-table-column>
            </el-table>
            
             <div class="pagination-container" style="text-align:right">
                <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listQuery.total"
                    :current-page.sync="listQuery.page"
                    :page-sizes="config.pageSizes"
                    :page-size="config.pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
    </div>
</template>
<script>
    import moment from 'moment';
    import validate from '@/utils/validate';
    import {getDetailForTask, rechargeById, deleteDetailById} from 'api/newTask';
    import TableLayout from 'components/TableLayout';
    import school from 'components/SchoolClasss/school';
    import { mapState, mapActions, mapGetters } from 'vuex'
    
    export default{
        name: 'detailList',
        components: {TableLayout, school},
        data() {
            return {
                taskId: this.$route.params.id,
                taskName: this.$route.params.taskName,
                formData: {
                    schoolId: '', // 学校Id
                    schoolName: '',
                    phone: '',
                    name: '',
                    exueID: '',
                    state: '',
                    daterange: [], 
                    options: [{
                        value: '',
                        label: '全部'
                    }, {
                        value: '1',
                        label: '待充值'
                    }, {
                        value: '0',
                        label: '已充值'
                    }]
                },
                detailList: [],
                addState: false,
                loading: false,
                dataNum: 1, // 表格1显示条数，初始为1
                listQuery: { // 分页
                    page: 1,
                    total: 0
                },
                multipleSelection: [], // 选中的列表项
                rules: {
                    exueID: [...validate.exueCode()]
                }
                

            }
        },
        mounted() {
            this.getDetail();
        },
        computed: {
            ...mapState({
                config: state => state.config.table
            }),
            ...mapGetters(['uid', 'token'])
        },
        methods: {
           
            // 全局获取行数
            ...mapActions(['ChangePageSize']), 

            handleSizeChange(val) {
                this.listQuery.page = 1;
                this.ChangePageSize(val);
                this.loading = true; 
                this.getDetail();               
            },
            //  功能：当前页码数
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.loading = true;  
                this.getDetail() ;          
            },
           
            // 学校名称输入匹配
            querySearch(queryString, cb) {
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },

            createFilter(queryString) {
                return (restaurant) => {
                    return (restaurant.value.indexOf(queryString.toLowerCase()) === 0);
                };
            },

            // 勾选列表项
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            
            schoolChange(val) {
                this.formData.schoolId = val
            },
           

            // 详情列表
            getDetail(form ='formData') {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        let startDate = this.formData.daterange[0]?moment(this.formData.daterange[0]).format('YYYY-MM-DD HH:mm:ss'):'';
                        let endDate = this.formData.daterange[1]?moment(this.formData.daterange[1]).format('YYYY-MM-DD')+' 23:59:59':'';
                        if (this.taskId && this.listQuery.page && this.config.pageSize) {
                            this.loading = true;
                            getDetailForTask(this.taskId, this.listQuery.page, this.config.pageSize, this.formData.schoolId, this.formData.phone,
                                this.formData.name, this.formData.exueID, this.formData.state, startDate, endDate).then(data => {
                                    this.loading = false;
                                    this.detailList = data.data.content.list;
                                    this.listQuery.total = data.data.content.pagination.total;
                                })
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
               
            },

            // 点击查询
            onSubmit() {
                this.listQuery.page = 1;
                this.getDetail();     
            },

            // 确认充值
            recharge() {
                if (!this.multipleSelection.length) {
                    return this.$message({
                        type: 'error',
                        message: '暂无勾选项'
                    })
                }
                this.$confirm('是否确认选中项均已完成充值？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    let list = [];
                    this.multipleSelection.forEach(item => {
                        if (item.status === '1') {
                            list.push(item.id);
                        }
                    })
                    if (list.length) {
                        rechargeById(list).then(data => {
                            this.$message({
                                type: 'success',
                                message: data.data.errorMsg
                            });
                            this.getDetail();
                        })   
                    } else {
                        this.$message({
                            type: 'error',
                            message: '已充值完毕，请不要重复充值！'
                        })
                    }              
                }).catch(() => {
                    // console.log() ;        
                });
            },
            
            // 删除
            delDetail() {
                if (!this.multipleSelection.length) {
                    return this.$message({
                        type: 'error',
                        message: '暂无勾选项'
                    })
                }
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    let list = this.multipleSelection.map(item => {
                        return item.id;
                    })
                    deleteDetailById(list).then(data => {
                        this.$message({
                            type: 'success',
                            message: data.data.errorMsg
                        });
                        this.getDetail();
                    })
                                
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },

            // 导出
            toExcel() {
                let startDate = this.formData.daterange[0]?moment(this.formData.daterange[0]).format('YYYY-MM-DD HH:mm:ss'):'';
                let endDate = this.formData.daterange[1]?moment(this.formData.daterange[1]).format('YYYY-MM-DD')+' 23:59:59':'';
                if (this.taskId) {
                    window.location.href = `${LOCAL_API.yy2}/task/findTaskDetailsByExcel?taskId=${this.taskId}&schoolId=${this.formData.schoolId}&teacherName=${this.formData.name}&exueCode=${this.formData.exueID}&status=${this.formData.state}&startDate=${startDate}&endDate=${endDate}&rechargePhone=${this.formData.phone}&taskName=${this.taskName}&token=${this.token}`;        
                }

            },
            fn(e) {
                // console.log(e)
                return Object.is(e.status, '1');
            }
           
        }
    }
    
</script>

<style lang="scss" scoped>
.addButton
{
    margin-bottom:20px;
}
.form-item-title {
            margin: 40px 0;
            font-size: 14px;
            color: #333;
            line-height: 14px;
            border-left: 4px solid #ff5e2c;
            text-indent: 16px;
        }

</style>